package testApplets;

import processing.core.PApplet;

public class CodeRepairApplet extends PApplet {

	public void setup() {
		String[] lines = this.loadStrings(this.selectInput());
		String[] newLines = new String[lines.length];
		for (int i = 0; i < lines.length; i++) {
			String line = lines[i];
			String newLine = replaceF(line);
			newLine = replace(newLine, "int(", "getInt(");
			newLine = replace(newLine, "float(", "getFloat(");
			newLine = replace(newLine, "char(", "getChar(");
			newLine = replace(newLine, "color ", "int ");
			//newLine=removewhiteSpace(newLine);
			if (newLine.startsWith("void")){
				newLine="public "+newLine;
			}
			newLines[i] = newLine;
		}
		
		this.saveStrings(this.selectOutput(), newLines);
		println("saved");
	}

	public String removewhiteSpace(String line){
		String newLine = "";
		for (int j = 0; j < line.length(); j++) {
			char c = line.charAt(j);
			if (c!=' '){
				newLine+=c;
			}
		}
		return newLine;	
	}
	public String replaceF(String line) {
		String newLine = "";
		String mode = "noPoint";
		for (int j = 0; j < line.length(); j++) {
			char c = line.charAt(j);
			if (c == '.') {
				mode = "point";
			} else if (Character.isDigit(c)) {
				if (mode.equals("point")) {
					mode = "number after point";
				}
			} else if (mode.equals("number after point")) {
				println(mode);
				if (c != 'F' && c != 'f') {
					println("insert F");
					mode = "noPoint";
					newLine += "f";
				} else {
					mode = "noPoint";
				}
			} else {
				mode = "noPoint";
			}
			newLine += c;
		}
		return newLine;
	}

	public String replace(String line, String match, String replace) {
		String newLine = "";
		int matchL = match.length();
		for (int j = 0; j < line.length(); j++) {
			boolean found = false;
			if (j < line.length() - matchL) {
				String sub = line.substring(j, j + matchL);

				if (sub.equals(match)) {
					int jPrev = j - 1;
					if (jPrev >= 0) {
						char c = line.charAt(jPrev);
						if (!Character.isLetter(c)) {
							found = true;
							newLine += replace;
							j += (matchL-1);
						}
					}
				}
			}
			if (!found)
				newLine += line.charAt(j);
		}
		return newLine;
	}
}
